<template>
  <div class="cos-status-root">
    <!-- 顶部详情表（竖向，铺满宽度） -->
    <a-table
      :columns="detailColumns"
      :dataSource="detailData"
      :pagination="false"
      bordered
      class="cos-detail-table"
      size="middle"
      rowKey="label"
      style="margin-bottom: 32px; width: 100%"
      showHeader="false"
    />
    <!-- 统计图一行展示 -->
    <div class="cos-charts-row">
      <div class="cos-chart-block">
        <VChart :option="usageProgressOption" autoresize style="height: 260px; width: 100%" />
      </div>
      <div class="cos-chart-block">
        <VChart :option="fileBarOption" autoresize style="height: 260px; width: 100%" />
      </div>
      <div class="cos-chart-block">
        <VChart :option="typeColumnOption" autoresize style="height: 260px; width: 100%" />
      </div>
    </div>
    <!-- 更新时间 -->
    <div class="cos-footer">数据时间：{{ formatDate(timestamp) }}</div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, onActivated, onDeactivated, computed } from 'vue'
  import { getCosStatus } from '@/api/guanliyuanmokuaijiekou'
  import VChart from 'vue-echarts'
  import dayjs from 'dayjs'

  const usage = ref<any>({})
  const bucketInfo = ref<any>({})
  const analysis = ref<any>({})
  const timestamp = ref<number>(0)

  let timer: ReturnType<typeof setInterval> | null = null

  const fetchCosStatus = async () => {
    const res = await getCosStatus()
    if (res.data.code === 200 && res.data.data) {
      usage.value = res.data.data.usage || {}
      bucketInfo.value = res.data.data.bucketInfo || {}
      analysis.value = res.data.data.analysis || {}
      timestamp.value = res.data.data.timestamp || 0
    }
  }

  function startTimer() {
    if (timer) return
    fetchCosStatus()
    timer = setInterval(fetchCosStatus, 1000)
  }
  function stopTimer() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  onMounted(startTimer)
  onActivated(startTimer)
  onUnmounted(stopTimer)
  onDeactivated(stopTimer)

  const formatSize = (bytes?: number) => {
    if (!bytes) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }
  const formatDate = (ts: number) => {
    if (!ts) return '-'
    return dayjs(ts).format('YYYY-MM-DD HH:mm:ss')
  }

  // 顶部详情表配置
  const detailColumns = [
    { title: '', dataIndex: 'label', key: 'label', width: 120 },
    {
      title: '',
      dataIndex: 'value',
      key: 'value',
      customRender: ({ record }: any) => record.value,
    },
  ]
  const detailData = computed(() => [
    { label: '桶名', value: bucketInfo.value.name || '-' },
    { label: '区域', value: bucketInfo.value.region || '-' },
    { label: '版本控制', value: bucketInfo.value.versioning || '-' },
    {
      label: '访问域名',
      value: bucketInfo.value.endpoint
        ? `<a href='${bucketInfo.value.endpoint}' target='_blank'>${bucketInfo.value.endpoint}</a>`
        : '-',
    },
    { label: '权限', value: bucketInfo.value.acl || '-' },
    { label: '生命周期', value: bucketInfo.value.lifecycle || '-' },
    { label: '日志', value: bucketInfo.value.logging || '-' },
  ])

  // 用量环形进度条
  const usageProgressOption = computed(() => {
    const percent =
      typeof analysis.value.usagePercent === 'number'
        ? Math.round(analysis.value.usagePercent * 100)
        : 0
    return {
      title: {
        text: '总用量',
        left: 'center',
        top: 20,
        textStyle: { fontSize: 18, color: '#0057b8', fontWeight: 600 },
        subtext: `对象数: ${usage.value.objectCount ?? '-'}`,
        subtextStyle: { fontSize: 14, color: '#888', fontWeight: 400, padding: [8, 0, 0, 0] },
      },
      series: [
        {
          type: 'pie',
          radius: ['80%', '95%'],
          avoidLabelOverlap: false,
          label: { show: false },
          data: [
            { value: percent, name: '已用', itemStyle: { color: '#1890ff' } },
            { value: 100 - percent, name: '未用', itemStyle: { color: '#e6f0ff' } },
          ],
          emphasis: { disabled: true },
        },
      ],
      graphic: [
        {
          type: 'text',
          left: 'center',
          top: '45%',
          style: {
            text: percent + '%',
            textAlign: 'center',
            fontSize: 32,
            fontWeight: 700,
            fill: '#0057b8',
          },
        },
        {
          type: 'text',
          left: 'center',
          top: '62%',
          style: {
            text: formatSize(usage.value.totalSize),
            textAlign: 'center',
            fontSize: 16,
            fill: '#222',
          },
        },
      ],
    }
  })

  // 文件大小分布横向条形图
  const fileBarOption = computed(() => {
    return {
      title: {
        text: '文件大小分布',
        left: 'center',
        top: 20,
        textStyle: { fontSize: 18, color: '#0057b8', fontWeight: 600 },
        subtext: `最大: ${formatSize(usage.value.maxFileSize)} 最小: ${formatSize(usage.value.minFileSize)}`,
        subtextStyle: { fontSize: 14, color: '#888', fontWeight: 400, padding: [8, 0, 0, 0] },
      },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: 80, right: 40, top: 70, bottom: 40 },
      xAxis: {
        type: 'value',
        axisLabel: {
          fontSize: 15,
          formatter: (val: number) => formatSize(val),
        },
        splitLine: { show: true },
        minInterval: 1,
      },
      yAxis: {
        type: 'category',
        data: ['平均', '最大', '最小'],
        axisLabel: { fontSize: 15 },
      },
      series: [
        {
          data: [
            usage.value.avgFileSize ?? 0,
            usage.value.maxFileSize ?? 0,
            usage.value.minFileSize ?? 0,
          ],
          type: 'bar',
          barWidth: 32,
          itemStyle: {
            color: function (params: { dataIndex: number }) {
              return ['#1890ff', '#36cfc9', '#b37feb'][params.dataIndex]
            },
            borderRadius: [8, 8, 8, 8],
          },
          label: {
            show: true,
            position: 'right',
            formatter: (val: any) => formatSize(val.value),
            fontSize: 14,
          },
        },
      ],
    }
  })

  // 类型分布柱状图
  const typeColumnOption = computed(() => {
    const dist = usage.value.typeDistribution || {}
    const data = [
      { name: 'JPG', value: dist.jpg?.count || 0 },
      { name: 'PNG', value: dist.png?.count || 0 },
      { name: '其他', value: dist.other?.count || 0 },
    ]
    const total = data.reduce((sum, d) => sum + d.value, 0)
    return {
      title: {
        text: '类型分布',
        left: 'center',
        top: 20,
        textStyle: { fontSize: 20, color: '#0057b8', fontWeight: 700 },
      },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: 40, right: 40, top: 70, bottom: 40 },
      xAxis: {
        type: 'category',
        data: data.map(d => d.name),
        axisLabel: { fontSize: 18, fontWeight: 'bold' },
      },
      yAxis: {
        type: 'value',
        axisLabel: { fontSize: 16 },
        minInterval: 1,
      },
      series: [
        {
          data: data.map(d => ({
            value: d.value,
            percent: total ? ((d.value / total) * 100).toFixed(2) : '0.00',
          })),
          type: 'bar',
          barWidth: 48,
          itemStyle: {
            color: ({ dataIndex }: { dataIndex: number }) =>
              ['#3b6cff', '#7ed957', '#ffc53d'][dataIndex],
            borderRadius: [8, 8, 0, 0],
          },
          label: {
            show: true,
            position: 'top',
            formatter: (params: any) => `${params.value} (${params.data.percent}%)`,
            fontSize: 18,
            fontWeight: 'bold',
          },
        },
      ],
    }
  })
</script>

<style scoped>
  .cos-status-root {
    background: var(--theme-background);
    min-height: 100vh;
    padding: 32px 18px 24px 18px;
    transition: all 0.3s ease;
  }
  
  .cos-detail-table {
    width: 100%;
    margin-bottom: 32px;
  }
  
  .cos-charts-row {
    display: flex;
    gap: 32px;
    margin-bottom: 32px;
  }
  
  .cos-chart-block {
    flex: 1;
    min-width: 260px;
    background: var(--theme-surface);
    border-radius: 16px;
    box-shadow: 0 2px 12px var(--theme-shadow);
    padding: 18px 14px 14px 18px;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    border: 1px solid var(--theme-border);
  }
  
  .cos-footer {
    color: var(--theme-textSecondary);
    font-size: 13px;
    margin-top: 18px;
    text-align: right;
    transition: color 0.3s ease;
  }

  /* 确保所有元素都使用主题色 */
  .cos-status-root * {
    transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease;
  }

  /* 修复可能遗漏的卡片背景 */
  .cos-chart-block {
    background: var(--theme-surface) !important;
    border-color: var(--theme-border) !important;
    color: var(--theme-text) !important;
  }

  /* 修复可能遗漏的边框和阴影 */
  .cos-chart-block {
    border-color: var(--theme-border) !important;
    box-shadow: 0 2px 12px var(--theme-shadow) !important;
  }
</style>
